package com.omenkk.juc.jmm;

import com.omenkk.juc.util.Slepper;
import lombok.extern.slf4j.Slf4j;

public class demo1 {
    public static void main(String[] args) {
TwoPhaseTermination twoPhaseTermination=new TwoPhaseTermination();
twoPhaseTermination.start();
Slepper.sleep(10);
twoPhaseTermination.stop();
    }
}
@Slf4j
class TwoPhaseTermination{
    //监控线程
    private Thread monitorThread;
    //标记
    private volatile boolean stop;

    private volatile  boolean start;

    public TwoPhaseTermination() {
        this.stop = false;
        this.start=false;
    }

    public void start(){
        if(start)return;
        synchronized (this){
            if(start)return;
            start=true;
        }

        monitorThread=new Thread(()->{

            //判断线程是否停止
            while(true){
                Thread thread = Thread.currentThread();
                if(stop){
log.debug("料理后事");
return;
                }
                //线程没有被停止，运行业务逻辑
                try{
                    Thread.sleep(1000);
                    log.debug("执行监控记录");
                }catch (InterruptedException e){
                    //将中断标记重新设置为true
                    thread.interrupt();
                }
            }
        });
        monitorThread.start();
    }
    //停止监控线程
    public void stop(){
        stop=true;
        monitorThread.interrupt();
    }
}
